package com.yc.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 二维码生成工具类
 */
@Slf4j
public class QRCodeUtil {

    // 默认二维码尺寸
    private static final int DEFAULT_WIDTH = 300;
    private static final int DEFAULT_HEIGHT = 300;

    /**
     * 生成带logo的二维码
     * @param content 二维码内容
     * @param logoText 中央显示的文字（如果没有logo图片）
     * @return 二维码图片的InputStream
     */
    public static InputStream generateQRCodeWithText(String content, String logoText) {
        try {
            // 生成二维码
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, DEFAULT_WIDTH, DEFAULT_HEIGHT);

            // 转换为BufferedImage
            BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

            // 在二维码中央添加文字
            if (logoText != null && !logoText.trim().isEmpty()) {
                qrImage = addTextToQRCode(qrImage, logoText);
            }

            // 转换为InputStream
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(qrImage, "PNG", baos);
            return new ByteArrayInputStream(baos.toByteArray());

        } catch (WriterException | IOException e) {
            log.error("生成二维码失败: {}", e.getMessage(), e);
            throw new RuntimeException("生成二维码失败", e);
        }
    }

    /**
     * 生成普通二维码
     * @param content 二维码内容
     * @return 二维码图片的InputStream
     */
    public static InputStream generateQRCode(String content) {
        return generateQRCode(content, DEFAULT_WIDTH, DEFAULT_HEIGHT);
    }

    /**
     * 生成指定尺寸的二维码
     * @param content 二维码内容
     * @param width 宽度
     * @param height 高度
     * @return 二维码图片的InputStream
     */
    public static InputStream generateQRCode(String content, int width, int height) {
        try {
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height);

            BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(qrImage, "PNG", baos);
            return new ByteArrayInputStream(baos.toByteArray());

        } catch (WriterException | IOException e) {
            log.error("生成二维码失败: {}", e.getMessage(), e);
            throw new RuntimeException("生成二维码失败", e);
        }
    }

    /**
     * 在二维码中央添加文字
     * @param qrImage 原始二维码图片
     * @param text 要添加的文字
     * @return 添加文字后的图片
     */
    private static BufferedImage addTextToQRCode(BufferedImage qrImage, String text) {
        Graphics2D graphics = qrImage.createGraphics();

        // 设置渲染质量
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // 设置字体
        Font font = new Font("微软雅黑", Font.BOLD, 16);
        graphics.setFont(font);

        // 获取文字尺寸
        FontMetrics fontMetrics = graphics.getFontMetrics();
        int textWidth = fontMetrics.stringWidth(text);
        int textHeight = fontMetrics.getHeight();

        // 计算文字位置（居中）
        int x = (qrImage.getWidth() - textWidth) / 2;
        int y = (qrImage.getHeight() + textHeight) / 2 - fontMetrics.getDescent();

        // 绘制白色背景矩形
        int padding = 8;
        graphics.setColor(Color.WHITE);
        graphics.fillRoundRect(x - padding, y - textHeight + fontMetrics.getDescent() - padding,
                textWidth + 2 * padding, textHeight + 2 * padding, 10, 10);

        // 绘制边框
        graphics.setColor(Color.GRAY);
        graphics.setStroke(new BasicStroke(1));
        graphics.drawRoundRect(x - padding, y - textHeight + fontMetrics.getDescent() - padding,
                textWidth + 2 * padding, textHeight + 2 * padding, 10, 10);

        // 绘制文字
        graphics.setColor(Color.BLACK);
        graphics.drawString(text, x, y);

        graphics.dispose();
        return qrImage;
    }
}